package com.oinux.playhelper.receiver;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.oinux.playhelper.db.DatabaseHelper;
import com.oinux.playhelper.entity.AppInfo;
import com.oinux.playhelper.entity.AppStat;
import com.oinux.playhelper.entity.Constants;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class ShutdownReceiver extends BroadcastReceiver {

	private static final String TAG = "shutdown...";

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(Constants.ACTION_SHUTDOWN)) {
			Log.v(TAG, "手机关闭中..");
			shutdown(context);
		}
	}

	private void shutdown(Context context) {
		DatabaseHelper databaseHelper = null;
		try {
			databaseHelper = OpenHelperManager.getHelper(context,
					DatabaseHelper.class);
			Dao<AppInfo, Integer> appInfoDao = databaseHelper.getAppInfoDao();
			Dao<AppStat, Integer> appStatDao = databaseHelper.getAppStatDao();
			List<AppInfo> appInfoList = appInfoDao.queryForAll();
			Date now = new Date();
			for (AppInfo appInfo : appInfoList) {
				appInfo.setTotalTime(appInfo.getTotalTime()
						+ appInfo.getRunTime());
				appInfo.setRunTime(0);
				appInfo.setMemSize(0);
				appInfo.setPid(0);
				appInfo.setUid(0);
				appInfo.setRunning(false);
				appInfoDao.update(appInfo);
			}
			QueryBuilder<AppStat, Integer> queryBuilder = appStatDao
					.queryBuilder();
			queryBuilder.where().isNull("finishTime");
			PreparedQuery<AppStat> preparedQuery = queryBuilder.prepare();
			List<AppStat> appStats = appStatDao.query(preparedQuery);
			for (AppStat appStat : appStats) {
				appStat.setFinishTime(now);
				appStatDao.update(appStat);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (databaseHelper != null) {
				OpenHelperManager.releaseHelper();
				databaseHelper = null;
			}
		}
	}
}